<template>
  <div>
    <el-dialog title="叠加子表" :visible.sync="subtableCartridgeCom" :close-on-click-modal="false"
               :close-on-press-escape="false" width="90%">
      <!-- 表格组件 -->
      <ex-base-table
        ref="exBaseTable"
        :tableColumn="tableColumn"
        :tableData="tableData"
        :loading.sync="loading"
        :isVxeCheckbox="false"
        @handleCreateEmit="handleCreateEmit"
        @handleUpdateEmit="handleUpdateEmit"
        @handleRmoveColEmit="handleRmoveColEmit"
      >
        <!-- 操作栏按钮扩展插槽 -->
        <template v-slot:handleExtend="{row}">
          &nbsp;
          <el-button v-if="true" size="mini" type="text" @click="limitingConditions(row)">
            限制条件
          </el-button>
        </template>
      </ex-base-table>


      <!-- 分页组件 -->
      <Pagination
        v-show="tablePage.totalResult>0"
        :total="tablePage.totalResult"
        :page.sync="tablePage.currentPage"
        :limit.sync="tablePage.pageSize"
        @pagination="pageFindList"
      />
    </el-dialog>


    <!-- 表单提价组件 -->
    <submit-form
      ref="submitForm"
      :dialogFormVisible.sync="dialogFormVisible"
      :dialogStatus="dialogStatus"
      :formSubmitData="formSubmitData"
      :parentData="parentData"
      :setList="setList"
      @handleFromCreateDataEmit="handleFromCreateDataEmit"
    >
    </submit-form>
    <!-- 修改表单组件 -->
    <!-- 表单提价组件 -->
    <update-form
      ref="updateForm"
      :dialogFormVisible.sync="dialogFormVisibleUpdate"
      :dialogStatus="dialogStatus"
      :formSubmitData="formSubmitData"
      :parentData="parentData"
      @handleFromUpdateDataEmit="handleFromUpdateDataEmit"
      @handleFromCreateDataEmit="handleFromCreateDataEmit"
      @resetFormDataEmit="resetFormSubmitData"
    >
    </update-form>

    <!-- 限制条件 -->
    <limiting-conditions
      v-if="dialogFormLimitingConditions"
      :dialogFormLimitingConditions.sync="dialogFormLimitingConditions"
      :limitingConditionsData="limitingConditionsData"
    >
    </limiting-conditions>
  </div>
</template>

<script>
// 这里可以导入其他文件（比如：组件，工具js，第三方插件js，json文件，图片文件等等）
// import PageHeaderLayout from '@/layouts/PageHeaderLayout'
// import ApeDrawer from '@/components/ApeDrawer'
// import { mapGetters } from 'vuex'

// 基础表格组件
import ExBaseTable from '@/components/VxeTable/ExBaseTable'
// 分页
import Pagination from '@/components/Pagination'
// 新增
import SubmitForm from './components/SubmitForm'

import resetFormSubmitData from '@/views/mixins/resetFormSubmitData'
import UpdateForm from './components/UpdateForm'
import limitingConditions from './components/LimitingConditions/index'

import {
  queryData,
  findAtermList,
  findcvtype,
  findBtermList,
  addS,
  delS,
  updateS
} from './service/baseApi'

export default {
  name: '',
  mixins: [resetFormSubmitData],
  components: {
    ExBaseTable,
    Pagination,
    SubmitForm,
    UpdateForm,
    limitingConditions
  },
  // 定义属性
  data() {
    return {
      // 表单数据对象
      formSubmitData: {
        id: '',
        a_term_weight: '',
        b_term_weight: '',
        operator: '',
        remark: ''
      },
      initFormSubmitData: {
        id: '',
        a_term_weight: '',
        b_term_weight: '',
        operator: '',
        remark: ''
      },
      /* 表单相关 */
      dialogFormVisible: false, // 修改删除弹出框
      dialogStatus: '',
      /* 表格相关 */
      tableColumn: [], // 表格字段
      loading: false, //表格loading特效
      tableData: [],  //表格数据
      /* 分页相关 */
      tablePage: {
        currentPage: 1, //当前页
        pageSize: 10,  // 每一页页数
        totalResult: 0
      },
      setList: new Array,
      // 修改相关
      dialogFormVisibleUpdate: false,//修改弹框
      dialogFormLimitingConditions: false,//限制条件弹框
      limitingConditionsData: {},

    }
  },
  props: {
    subtableCartridge: {
      type: Boolean,
      default: false
    },
    parentData: {
      type: Object,
      default: function () {
        return {
          id: undefined,
          remark: '',
        }
      }
    },
  },
  // 计算属性，会监听依赖属性值随之变化
  computed: {
    subtableCartridgeCom: {
      get() {
        return this.subtableCartridge
      },
      set(val) {
        this.$emit('update:subtableCartridge', val)
      }
    },
  },
  // 监控data中的数据变化
  watch: {},
  // 方法集合
  methods: {
    /* API数据操作相关 */

    async collectionData() {
      var collection = new Array;
      var collectionA = new Array;
      // 获取合集
      await findcvtype({
        a_cv_type: this.parentData.a_cv_type,
        a_cv_code: this.parentData.a_cv_code,
        b_cv_type: this.parentData.b_cv_type,
        b_cv_code: this.parentData.b_cv_code
      }).then(({data}) => {
        // this.movementCurveType = data.rows
        collection = data.rows
        console.log(collection, '合集')
      })
      // 获取a合集
      await findAtermList({
        a_cv_type: this.parentData.a_cv_type,
        a_cv_code: this.parentData.a_cv_code
      }).then(({data}) => {
        collectionA = data.rows
      })
      // 获取b合集
      await findBtermList({
        b_cv_type: this.parentData.b_cv_type,
        b_cv_code: this.parentData.b_cv_code
      }).then(({data}) => {
        //  a合集数据拼接
        collection.map((item, index) => {
          collectionA.map(dataA => {
            if (item.term_name == dataA.term_name) {
              this.$set(collection[index], 'a_term_name', true)
              this.$set(collection[index], 'a_val', '')
              this.$set(collection[index], 'check', '1')
            }
          })
          if (index == collection.length - 1) {
            collection.map((item, index) => {
              if (!item.hasOwnProperty('a_term_name')) {
                this.$set(collection[index], 'a_term_name', false)
                this.$set(collection[index], 'a_val', '')
                this.$set(collection[index], 'check', '1')
              }
            })
          }
        })


        //  b合集数据拼接
        collection.map((item, index) => {
          data.rows.map(dataB => {
            if (item.term_name == dataB.term_name) {
              this.$set(collection[index], 'b_term_name', true)
              this.$set(collection[index], 'b_val', '')
            }
          })
          if (index == collection.length - 1) {
            collection.map((item, index) => {
              if (!item.hasOwnProperty('b_term_name')) {
                this.$set(collection[index], 'b_term_name', false)
                this.$set(collection[index], 'b_val', '')
              }
            })
          }
        })
        this.setList = collection
      })
    },
    // 查询数据
    findList() {
      this.loading = true
      // 请求表格数据
      queryData({
        page: this.tablePage.currentPage, // 当前页
        pageSize: this.tablePage.pageSize, // 每页条数
        id: this.parentData.id
      }).then(({data}) => {
        console.log(data)
        // 给表格数据赋值
        this.tableData = data.rows
        // 给分页总数赋值
        this.tablePage.totalResult = data.total
        // 关闭加载特效
        setTimeout(() => {
          this.loading = false
        }, 0.5 * 1000)
      }, error => {
        console.log('getList:error', error);
        // alert(error);
      })
    },
    /* 分页组件相关 */
    // 分页事件（页码切换，每页页数切换）
    pageFindList() {
      this.findList()
    },
    /* 表格组件相关 */
    // 初始化表格字段
    initTableCols() {
      const tabCols = [  //动态增加的字段 传进来的
        {field: 'term_name', title: '期限名称', width: 300},
        {field: 'a_term_weight', title: this.parentData.a_cv_name,},
        {field: 'operatorname', title: '运算符（+、-、*、/）', width: 300},
        {field: 'b_term_weight', title: this.parentData.b_cv_name},
      ]
      this.tableColumn = tabCols;
    },
    // 表格工具组-新增表单弹窗（需要表单组件）
    handleCreateEmit(type) {
      // 重置表单内容
      this.resetFormSubmitData()
      this.dialogStatus = type
      this.dialogFormVisible = true
      // this.$nextTick(() => {
      //   this.$refs.submitForm.$refs['dataForm'].clearValidate()
      // })
    },
    /* 表单组件相关 */
    // 更新
    handleFromUpdateDataEmit() {
      updateS({
        ...this.formSubmitData,  //检索条件
      }).then(({data}) => {
        console.log('response:....', data);
        this.findList()
        // 关闭加载特效
      }, error => {
        console.log('getList:error', error);
        // alert(error);
      })
    },
    // 增加
    handleFromCreateDataEmit(obj) {
      addS({
        ...obj  //检索条件
      }).then(({data}) => {
        console.log('response:....', data);
        this.findList()
        // 关闭加载特效
      }, error => {
        console.log('getList:error', error);
        // alert(error);
      })
    },
    // 行内按钮-修改数据弹窗（需要表单组件）
    handleUpdateEmit(row, type) {
      this.formSubmitData = Object.assign({}, row) // copy obj
      this.resetFormSubmitData({
        resetObj: Object.assign({}, row),
        replaceObj: {
          remark: ''
        }
      })
      this.dialogFormVisibleUpdate = true

      this.$nextTick(() => {
        this.$refs.updateForm.$refs['dataForm'].clearValidate()
      })
    },
    // 单行删除
    handleRmoveColEmit(row) {
      console.log(row)
      delS({
        id: row.id
      }).then(({data}) => {
        this.findList()
      })
    },
    // 限制条件
    limitingConditions(row) {
      console.log(row)
      this.limitingConditionsData = Object.assign({}, row)
      this.dialogFormLimitingConditions = true
    }

  },
  // 生命周期 - 创建完成（可以访问当前this实例）
  created() {
    // 初始化表格字段
    this.initTableCols()
    // 初始化表格数据
    this.findList()
    // 获取合集数据
    this.collectionData()
  },
  // 生命周期 - 挂载完成（可以访问DOM元素）
  mounted() {

  },
  beforeCreate() {
  }, // 生命周期 - 创建之前
  beforeMount() {
  }, // 生命周期 - 挂载之前
  beforeUpdate() {
  }, // 生命周期 - 更新之前
  updated() {
  }, // 生命周期 - 更新之后
  beforeDestroy() {
  }, // 生命周期 - 销毁之前
  destroyed() {
  }, // 生命周期 - 销毁完成
  activated() {
  }, // 如果页面有keep-alive缓存功能，这个函数会触发
}
</script>

<style lang='scss' scoped>

</style>
